#r,w = IO.pipe
require 'em-websocket'
require 'drb'

Rails.logger.info "In Init pid is #{Process.pid}"

DRb.start_service
$share = DRbObject.new(nil,"druby://0.0.0.0:4000")

#fork do
Thread.new do
  EM.run {
    EM::WebSocket.run(:host => "0.0.0.0", :port => 8080, :debug => false) do |ws|
      ws.onopen { |handshake|
        puts "WebSocket opened #{{
          :path => handshake.path,
          :query => handshake.query,
          :origin => handshake.origin,
        }}"

        ws.send "Hello Client!"
        $share.add_client(ws)
        #$g_clients << ws
        #$g_clients.each do |clt|
        $share.all_clients.each do |clt|
          clt.send("[#{$share.all_clients.count}]每一个人都有!!!")
        end
      }
      ws.onmessage { |msg|
        p "svr get msg : #{msg}"
        ws.send "Pong: #{msg}"
      }
      ws.onclose {
        puts "WebSocket closed"
      }
      ws.onerror { |e|
        puts "Error: #{e.message}"
      }
    end
  }
end
